[[...path]].page.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUser, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import {
  11. GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { useCurrentGrowiLayoutFluidClassName } from '~/client/services/layout';
  19. import { Comments } from '~/components/Comments';
  20. import { MainPane } from '~/components/Layout/MainPane';
  21. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  22. // import { useTranslation } from '~/i18n';
  23. import { PageContentFooter } from '~/components/PageContentFooter';
  24. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  25. import { UsersHomePageFooterProps } from '~/components/UsersHomePageFooter';
  26. import type { CrowiRequest } from '~/interfaces/crowi-request';
  27. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  28. // import { useRendererSettings } from '~/stores/renderer';
  29. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  30. import type { EditorConfig } from '~/interfaces/editor-settings';
  31. import type { RendererConfig } from '~/interfaces/services/renderer';
  32. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  33. import type { IUserUISettings } from '~/interfaces/user-ui-settings';
  34. import type { PageModel, PageDocument } from '~/server/models/page';
  35. import type { PageRedirectModel } from '~/server/models/page-redirect';
  36. import type { UserUISettingsModel } from '~/server/models/user-ui-settings';
  37. import { useEditingMarkdown } from '~/stores/editor';
  38. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  39. import { useSWRxCurrentPage, useSWRxIsGrantNormalized } from '~/stores/page';
  40. import { useRedirectFrom } from '~/stores/page-redirect';
  41. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  42. import {
  43. useSelectedGrant,
  44. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  45. } from '~/stores/ui';
  46. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  47. import loggerFactory from '~/utils/logger';
  48. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  49. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  50. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  51. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  52. import { BasicLayoutWithEditorMode } from '../components/Layout/BasicLayout';
  53. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  54. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  55. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  56. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  57. import type { PageSideContentsProps } from '../components/PageSideContents';
  58. import {
  59. useCurrentUser,
  60. useIsLatestRevision,
  61. useIsForbidden, useIsNotFound, useIsSharedUser,
  62. useIsEnabledStaleNotification, useIsIdenticalPath,
  63. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  64. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  65. useIsAclEnabled, useIsSearchPage, useTemplateTagData, useTemplateBodyData, useIsEnabledAttachTitleHeader,
  66. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  67. useIsSlackConfigured, useRendererConfig,
  68. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  69. } from '../stores/context';
  70. import { NextPageWithLayout } from './_app.page';
  71. import {
  72. CommonProps, getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage,
  73. } from './utils/commons';
  74. declare global {
  75. // eslint-disable-next-line vars-on-top, no-var
  76. var globalEmitter: EventEmitter;
  77. }
  78. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  79. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  80. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  81. const PageSideContents = dynamic<PageSideContentsProps>(() => import('../components/PageSideContents').then(mod => mod.PageSideContents), { ssr: false });
  82. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  83. const UsersHomePageFooter = dynamic<UsersHomePageFooterProps>(() => import('../components/UsersHomePageFooter')
  84. .then(mod => mod.UsersHomePageFooter), { ssr: false });
  85. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  86. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  87. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  88. const logger = loggerFactory('growi:pages:all');
  89. const {
  90. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isCreatablePage, isTopPage,
  91. } = pagePathUtils;
  92. const { removeHeadingSlash } = pathUtils;
  93. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  94. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  95. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  96. {
  97. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  98. return v?.data != null
  99. && v?.data.toObject != null
  100. && v?.meta != null
  101. && isIPageInfoForEntity(v.meta);
  102. },
  103. serialize: (v) => {
  104. return {
  105. data: superjson.stringify(v.data.toObject()),
  106. meta: superjson.stringify(v.meta),
  107. };
  108. },
  109. deserialize: (v) => {
  110. return {
  111. data: superjson.parse(v.data),
  112. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  113. };
  114. },
  115. },
  116. 'IPageToShowRevisionWithMetaTransformer',
  117. );
  118. // GrowiContextualSubNavigation for NOT shared page
  119. type GrowiContextualSubNavigationProps = {
  120. isLinkSharingDisabled: boolean,
  121. }
  122. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  123. const { isLinkSharingDisabled } = props;
  124. const { data: currentPage } = useSWRxCurrentPage();
  125. if (currentPage == null) { return <></> }
  126. return <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>;
  127. };
  128. const IdenticalPathPage = (): JSX.Element => {
  129. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  130. return <IdenticalPathPage />;
  131. };
  132. const PutbackPageModal = (): JSX.Element => {
  133. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  134. return <PutbackPageModal />;
  135. };
  136. type Props = CommonProps & {
  137. currentUser: IUser,
  138. pageWithMeta: IPageToShowRevisionWithMeta | null,
  139. // pageUser?: any,
  140. redirectFrom?: string;
  141. // shareLinkId?: string;
  142. isLatestRevision?: boolean,
  143. isIdenticalPathPage?: boolean,
  144. isForbidden: boolean,
  145. isNotFound: boolean,
  146. isNotCreatable: boolean,
  147. // isAbleToDeleteCompletely: boolean,
  148. templateTagData?: string[],
  149. templateBodyData?: string,
  150. isSearchServiceConfigured: boolean,
  151. isSearchServiceReachable: boolean,
  152. isSearchScopeChildrenAsDefault: boolean,
  153. isSlackConfigured: boolean,
  154. // isMailerSetup: boolean,
  155. isAclEnabled: boolean,
  156. // hasSlackConfig: boolean,
  157. drawioUri: string | null,
  158. hackmdUri: string,
  159. noCdn: string,
  160. // highlightJsStyle: string,
  161. isAllReplyShown: boolean,
  162. isContainerFluid: boolean,
  163. editorConfig: EditorConfig,
  164. isEnabledStaleNotification: boolean,
  165. isEnabledAttachTitleHeader: boolean,
  166. // isEnabledLinebreaks: boolean,
  167. // isEnabledLinebreaksInComments: boolean,
  168. adminPreferredIndentSize: number,
  169. isIndentSizeForced: boolean,
  170. disableLinkSharing: boolean,
  171. rendererConfig: RendererConfig,
  172. // UI
  173. userUISettings?: IUserUISettings
  174. // Sidebar
  175. sidebarConfig: ISidebarConfig,
  176. };
  177. const Page: NextPageWithLayout<Props> = (props: Props) => {
  178. // const { t } = useTranslation();
  179. const router = useRouter();
  180. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  181. // register global EventEmitter
  182. if (isClient() && window.globalEmitter == null) {
  183. window.globalEmitter = new EventEmitter();
  184. }
  185. // commons
  186. useEditorConfig(props.editorConfig);
  187. useCsrfToken(props.csrfToken);
  188. // UserUISettings
  189. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  190. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  191. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  192. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  193. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  194. // page
  195. useIsLatestRevision(props.isLatestRevision);
  196. useIsContainerFluid(props.isContainerFluid);
  197. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  198. useIsForbidden(props.isForbidden);
  199. useIsNotFound(props.isNotFound);
  200. useIsNotCreatable(props.isNotCreatable);
  201. useRedirectFrom(props.redirectFrom ?? null);
  202. useIsSharedUser(false); // this page cann't be routed for '/share'
  203. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  204. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  205. useIsSearchPage(false);
  206. useTemplateTagData(props.templateTagData);
  207. useTemplateBodyData(props.templateBodyData);
  208. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  209. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  210. useIsSearchServiceReachable(props.isSearchServiceReachable);
  211. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  212. useIsSlackConfigured(props.isSlackConfigured);
  213. // useIsMailerSetup(props.isMailerSetup);
  214. useIsAclEnabled(props.isAclEnabled);
  215. // useHasSlackConfig(props.hasSlackConfig);
  216. useDrawioUri(props.drawioUri);
  217. useHackmdUri(props.hackmdUri);
  218. // useNoCdn(props.noCdn);
  219. useDefaultIndentSize(props.adminPreferredIndentSize);
  220. useIsIndentSizeForced(props.isIndentSizeForced);
  221. useDisableLinkSharing(props.disableLinkSharing);
  222. useRendererConfig(props.rendererConfig);
  223. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  224. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  225. useIsAllReplyShown(props.isAllReplyShown);
  226. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  227. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  228. const { pageWithMeta, userUISettings } = props;
  229. const pageId = pageWithMeta?.data._id;
  230. const pagePath = pageWithMeta?.data.path ?? (!_isPermalink(props.currentPathname) ? props.currentPathname : undefined);
  231. useCurrentPageId(pageId ?? null);
  232. useRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  233. useRemoteRevisionId(pageWithMeta?.data.revision?._id);
  234. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  235. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  236. useCurrentPathname(props.currentPathname);
  237. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  238. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  239. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  240. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  241. useSetupGlobalSocket();
  242. useSetupGlobalSocketForPage(pageId);
  243. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName();
  244. const shouldRenderPutbackPageModal = pageWithMeta != null
  245. ? _isTrashPage(pageWithMeta.data.path)
  246. : false;
  247. // sync grant data
  248. useEffect(() => {
  249. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  250. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  251. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  252. useEffect(() => {
  253. const decodedURI = decodeURI(window.location.pathname);
  254. if (isClient() && decodedURI !== props.currentPathname) {
  255. const { search, hash } = window.location;
  256. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  257. }
  258. }, [props.currentPathname, router]);
  259. const isTopPagePath = isTopPage(pageWithMeta?.data.path ?? '');
  260. const title = generateCustomTitleForPage(props, pagePath ?? '');
  261. const sideContents = !props.isNotFound && !props.isNotCreatable
  262. ? (
  263. <PageSideContents page={pageWithMeta?.data} />
  264. )
  265. : <></>;
  266. const footerContents = !props.isIdenticalPathPage && !props.isNotFound && pageWithMeta != null
  267. ? (
  268. <>
  269. { pagePath != null && !isTopPagePath && (
  270. <Comments pageId={pageId} pagePath={pagePath} revision={pageWithMeta.data.revision} />
  271. ) }
  272. { isUsersHomePage(pageWithMeta.data.path) && (
  273. <UsersHomePageFooter creatorId={pageWithMeta.data.creator._id}/>
  274. ) }
  275. <PageContentFooter page={pageWithMeta.data} />
  276. </>
  277. )
  278. : <></>;
  279. return (
  280. <>
  281. <Head>
  282. <title>{title}</title>
  283. </Head>
  284. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  285. <header className="py-0 position-relative">
  286. <div id="grw-subnav-container">
  287. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  288. </div>
  289. </header>
  290. <div className="d-edit-none">
  291. <GrowiSubNavigationSwitcher />
  292. </div>
  293. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  294. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  295. <MainPane
  296. sideContents={sideContents}
  297. footerContents={footerContents}
  298. >
  299. <PageAlerts />
  300. { props.isIdenticalPathPage && <IdenticalPathPage />}
  301. { !props.isIdenticalPathPage && (
  302. <>
  303. { props.isForbidden && <ForbiddenPage /> }
  304. { props.isNotCreatable && <NotCreatablePage />}
  305. { !props.isForbidden && !props.isNotCreatable && <DisplaySwitcher />}
  306. </>
  307. ) }
  308. <PageStatusAlert />
  309. </MainPane>
  310. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  311. </div>
  312. </>
  313. );
  314. };
  315. Page.getLayout = function getLayout(page) {
  316. return (
  317. <>
  318. <DrawioViewerScript />
  319. <BasicLayoutWithEditorMode>
  320. {page}
  321. </BasicLayoutWithEditorMode>
  322. <UnsavedAlertDialog />
  323. <DescendantsPageListModal />
  324. <DrawioModal />
  325. <HandsontableModal />
  326. </>
  327. );
  328. };
  329. function getPageIdFromPathname(currentPathname: string): string | null {
  330. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  331. }
  332. class MultiplePagesHitsError extends ExtensibleCustomError {
  333. pagePath: string;
  334. constructor(pagePath: string) {
  335. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  336. this.pagePath = pagePath;
  337. }
  338. }
  339. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  340. const { model: mongooseModel } = await import('mongoose');
  341. const req: CrowiRequest = context.req as CrowiRequest;
  342. const { crowi } = req;
  343. const { revisionId } = req.query;
  344. const Page = crowi.model('Page') as PageModel;
  345. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  346. const { pageService } = crowi;
  347. let currentPathname = props.currentPathname;
  348. const pageId = getPageIdFromPathname(currentPathname);
  349. const isPermalink = _isPermalink(currentPathname);
  350. const { user } = req;
  351. if (!isPermalink) {
  352. // check redirects
  353. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  354. if (chains != null) {
  355. // overwrite currentPathname
  356. currentPathname = chains.end.toPath;
  357. props.currentPathname = currentPathname;
  358. // set redirectFrom
  359. props.redirectFrom = chains.start.fromPath;
  360. }
  361. // check whether the specified page path hits to multiple pages
  362. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  363. if (count > 1) {
  364. throw new MultiplePagesHitsError(currentPathname);
  365. }
  366. }
  367. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  368. const page = pageWithMeta?.data as unknown as PageDocument;
  369. // add user to seen users
  370. if (page != null && user != null) {
  371. await page.seen(user);
  372. }
  373. // populate & check if the revision is latest
  374. if (page != null) {
  375. page.initLatestRevisionField(revisionId);
  376. await page.populateDataToShowRevision();
  377. props.isLatestRevision = page.isLatestRevision();
  378. }
  379. if (page == null && user != null) {
  380. const templateData = await Page.findTemplate(props.currentPathname);
  381. if (templateData != null) {
  382. props.templateTagData = templateData.templateTags as string[];
  383. props.templateBodyData = templateData.templateBody as string;
  384. }
  385. }
  386. props.pageWithMeta = pageWithMeta;
  387. }
  388. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  389. const { model: mongooseModel } = await import('mongoose');
  390. const req = context.req as CrowiRequest<IUserHasId & any>;
  391. const { user } = req;
  392. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  393. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  394. if (userUISettings != null) {
  395. props.userUISettings = userUISettings.toObject();
  396. }
  397. }
  398. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  399. const req: CrowiRequest = context.req as CrowiRequest;
  400. const { crowi } = req;
  401. const Page = crowi.model('Page') as PageModel;
  402. const { currentPathname } = props;
  403. const pageId = getPageIdFromPathname(currentPathname);
  404. const isPermalink = _isPermalink(currentPathname);
  405. const page = props.pageWithMeta?.data;
  406. if (props.isIdenticalPathPage) {
  407. props.isNotCreatable = true;
  408. }
  409. else if (page == null) {
  410. props.isNotFound = true;
  411. props.isNotCreatable = !isCreatablePage(currentPathname);
  412. // check the page is forbidden or just does not exist.
  413. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  414. props.isForbidden = count > 0;
  415. }
  416. else {
  417. props.isNotFound = page.isEmpty;
  418. props.isNotCreatable = false;
  419. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  420. if (isPermalink && page.isEmpty) {
  421. props.currentPathname = page.path;
  422. }
  423. // /path/to/page ==> /62a88db47fed8b2d94f30000
  424. if (!isPermalink && !page.isEmpty) {
  425. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  426. if (!isToppage) {
  427. props.currentPathname = `/${page._id}`;
  428. }
  429. }
  430. }
  431. }
  432. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  433. // const req: CrowiRequest = context.req as CrowiRequest;
  434. // const { crowi } = req;
  435. // const UserModel = crowi.model('User');
  436. // if (isUserPage(props.currentPagePath)) {
  437. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  438. // if (user != null) {
  439. // props.pageUser = JSON.stringify(user.toObject());
  440. // }
  441. // }
  442. // }
  443. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  444. const req: CrowiRequest = context.req as CrowiRequest;
  445. const { crowi } = req;
  446. const {
  447. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  448. } = crowi;
  449. props.isSearchServiceConfigured = searchService.isConfigured;
  450. props.isSearchServiceReachable = searchService.isReachable;
  451. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  452. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  453. // props.isMailerSetup = mailService.isMailerSetup;
  454. props.isAclEnabled = aclService.isAclEnabled();
  455. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  456. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  457. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  458. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  459. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  460. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  461. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  462. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  463. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  464. props.editorConfig = {
  465. upload: {
  466. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  467. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  468. },
  469. };
  470. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  471. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  472. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  473. props.rendererConfig = {
  474. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  475. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  476. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  477. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  478. plantumlUri: process.env.PLANTUML_URI ?? null,
  479. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  480. // XSS Options
  481. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  482. tagWhiteList: crowi.xssService.getTagWhiteList(),
  483. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  484. // XSS: rehype-sanitize options
  485. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  486. };
  487. props.sidebarConfig = {
  488. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  489. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  490. };
  491. }
  492. /**
  493. * for Server Side Translations
  494. * @param context
  495. * @param props
  496. * @param namespacesRequired
  497. */
  498. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  499. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  500. props._nextI18Next = nextI18NextConfig._nextI18Next;
  501. }
  502. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  503. const req = context.req as CrowiRequest<IUserHasId & any>;
  504. const { user } = req;
  505. const result = await getServerSideCommonProps(context);
  506. // check for presence
  507. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  508. if (!('props' in result)) {
  509. throw new Error('invalid getSSP result');
  510. }
  511. const props: Props = result.props as Props;
  512. if (props.redirectDestination != null) {
  513. return {
  514. redirect: {
  515. permanent: false,
  516. destination: props.redirectDestination,
  517. },
  518. };
  519. }
  520. if (user != null) {
  521. props.currentUser = user.toObject();
  522. }
  523. try {
  524. await injectPageData(context, props);
  525. }
  526. catch (err) {
  527. if (err instanceof MultiplePagesHitsError) {
  528. props.isIdenticalPathPage = true;
  529. }
  530. else {
  531. throw err;
  532. }
  533. }
  534. await injectUserUISettings(context, props);
  535. await injectRoutingInformation(context, props);
  536. injectServerConfigurations(context, props);
  537. await injectNextI18NextConfigurations(context, props, ['translation']);
  538. return {
  539. props,
  540. };
  541. };
  542. export default Page;